package com.chuangyang.fixboxmaster.utils.pay.zhifubao;

import android.app.Activity;

import com.alipay.sdk.app.PayTask;
import com.chuangyang.fixboxmaster.bean.PayType;
import com.chuangyang.fixboxmaster.listener.PayListener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2015/5/6.
 */
public class ZhiFuBao {

    //商户PID
    private static final String PARTNER = "2088911428014390";
    //商户收款账号
    private static final String SELLER = "pay@creayoung.com";
    //商户私钥，pkcs8格式
    private static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANVhvUNJUcAHQKhB"+
            "udOYOV3j4mC7eMmMr1EOkOQhmMk0aFEz6WsNVa42mLRupOiEO2F2FijA1pkU8k44"+
            "TYWYYajoyKFwQ/Td9AEgtIdTKETSjgZlTx8hxUT7jiMmXczg2nxYyneHhjzngpim"+
            "zhGJqZYzR5gkBNHvqdXzNDVJdAurAgMBAAECgYBsSAoMICPNB6EnARt0pdXOsHrL"+
            "TbcwyCSbRIIAUpA+4kphkq9LtNua6Xe6cD9dAuVDQvJhweHkkv2W9flY5wf/CtOM"+
            "FqkOXU1l3mo5D/axXU58WAnkG6UK9DsOpVCG3ZKgi9RMhzkttM+xJE4yqdBbZaID"+
            "u912b8AST6QKlleEuQJBAOrp6RjG4mz8SXqkie8n+YcrWNvuX/rZp8S8fegQg6BC"+
            "O4xRyrEl4ntyFAFzPUjnis+mWeOFELS5xQdAf9KyCiUCQQDoiQvQL64Nwy/8tMzP"+
            "OSli7Qug3ohRVUhUjgXUkOKkZfyYHvrJifuGnkcsNPjwlE+uv3Iih9mzCEBnImiZ"+
            "oo2PAkEAkEGGH+36G70tjj++aHue0u++iIgwroW8babmlnyVp/MkSD3t/6zpEK90"+
            "M5PF3aA6cNuRtZMAOEsgAB0OoZ8tdQJAeHlYV3n8cUDpAcIiQlJZMNmjJqtkcM8A"+
            "dF5IgwK1iXsVTTLvt673U515PlwLhYkxZ1XkqiM8FNd3lndrPf3L3QJAIXnYnBOX"+
            "bezoItStxvH7/RAN4hY7yNSCr/bacY3cPSMmUj4XbzpS3//qo/zzYsqMjoDuOFEG"+
            "c+s/uTQh4rO75g==";
    //支付宝公钥
    private static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ" +
            "KBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBo" +
            "LPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC" +
            "2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

    private PayListener mPayListener;
    private Activity mActivity;

    public ZhiFuBao(Activity activity,PayListener listener){
        this.mActivity = activity;
        this.mPayListener = listener;
    }

    public void pay(String subject, String body, String orderID,String price){
        // 订单
        String orderInfo = getOrderInfo(subject, body,orderID, "0.01");// todo 0.01 test use

        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(mActivity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                mPayListener.onCallBack(PayType.PAY_TYPE_ZHIFUBAO,result);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * create the order info. 创建订单信息
     *
     */
    private String getOrderInfo(String subject, String body,String serialId, String price) {
        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + serialId + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://apiclient.creayoung.com/fixbox_app_server/appclient_index.php/Alipay/paySuccess"
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }


    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content
     *            待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     *
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }





}
